//
//  HSYBaseViewController+ALAsset.m
//  高仿暴走斗图
//
//  Created by key on 16/6/3.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "HSYBaseViewController+ALAsset.h"
#import "HSYBaseViewController+Alert.h"

static ALAssetsLibrary *library;
static NSMutableArray *groups;
static NSInteger number = 0;

@implementation HSYBaseViewController (ALAsset)

+ (ALAssetsLibrary *)shareInstanceLibrary {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        library = [[ALAssetsLibrary alloc] init];
    });
    
    return library;
}

+ (NSMutableArray *)shareInstanceGroups {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        groups = [[NSMutableArray alloc] init];
    });
    return groups;
}

/**
 *  获取设备图片库资源
 *
 *  @param type         资源类型
 *  @param block        获取资源路径的回调
 *  @param failureBlock 获取失败的回调
 *  @param completion   获取完所有资源后的回调
 */
- (void)openPhotoLibraryWithALAssetType:(kALAssetType)type nextImageURLBlock:(void(^)(ALAsset *asset))block failureBlock:(void(^)(NSError *error))failureBlock completion:(void(^)())completion {

    [self enumerationResultsBlock:^(ALAssetsGroup *group) {
        
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            
            if (result) {
                
                id object = [result valueForProperty:ALAssetPropertyType];
                NSString *typeString = [self getALAssetType:type];
                
                if([object isEqualToString:typeString]) {
                    block(result);
                    if ((index + 1) == number) {
                        completion();
                        number = 0;
                    }
                }
            }
        }];
    } assetType:type];
}

- (void)getAssetForURL:(NSURL *)url index:(NSInteger)index withImageDictionaryBlock:(void(^)(NSDictionary *dic, NSInteger index))block failureBlock:(void(^)(NSError *error))failureBlock {
    
    @autoreleasepool {
        [[HSYBaseViewController shareInstanceLibrary] assetForURL:url resultBlock:^(ALAsset *asset) {
            
            UIImage *fullScreenImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
            UIImage *thumbnailImage = [UIImage imageWithCGImage:[asset thumbnail]];
            
            block(@{
                    [fullScreenImage copy] : [thumbnailImage copy],
                    }, index);
            
        } failureBlock:^(NSError *error) {
            [HSYBaseViewController showAlertHUDWithMessage:HSYLOCALIZED(@"没有权限访问相册")];
            failureBlock(error);
        } ];
    }
}

- (NSString *)getALAssetType:(kALAssetType)type {
    
    NSString *assetString = nil;
    switch (type) {
        case kALAssetTypePhoto:
            assetString = ALAssetTypePhoto;
            break;
            
        case kALAssetTypeVideo:
            assetString = ALAssetTypeVideo;
            break;
            
        case kALAssetTypeUnknow:
            assetString = ALAssetTypeUnknown;
            break;
            
        default:
            break;
    }
    return assetString;
}


- (RACSignal *)rac_openPhotoLibraryWithALAssetType:(kALAssetType)type {
    
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        [self openPhotoLibraryWithALAssetType:type nextImageURLBlock:^(ALAsset *asset) {
            
            [subscriber sendNext:asset];
            
        } failureBlock:^(NSError *error) {
            
            [subscriber sendError:error];
            [subscriber sendCompleted];

        } completion:^{
            
            [subscriber sendCompleted];
            
        }];
        return nil;
    }];
}


- (void)enumerationResultsBlock:(void(^)(ALAssetsGroup *group))block assetType:(kALAssetType)type {
    
    //枚举回调
    ALAssetsLibraryGroupsEnumerationResultsBlock resultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
        
        if (group) {
            //设置过滤类型
            if (type == kALAssetTypePhoto || type == kALAssetTypeUnknow) {
                [group setAssetsFilter:[ALAssetsFilter allAssets]];
            } else {
                [group setAssetsFilter:[ALAssetsFilter allVideos]];
            }
            
            if (![[HSYBaseViewController shareInstanceGroups] containsObject:group]) {
                [[HSYBaseViewController shareInstanceGroups] addObject:group];
            }
            if ([group numberOfAssets] > 0) {
                number = [group numberOfAssets];
                block(group);
            }
        }
    };
    //枚举失败回调
    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
        [HSYBaseViewController showAlertHUDWithMessage:HSYLOCALIZED(@"没有权限访问相册")];
    };
    [self getAllGroupForResultsBlock:resultsBlock failureBlock:failureBlock assetType:type];
}


- (void)getAllGroupForResultsBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)resultsBlock failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock assetType:(kALAssetType)assetType {
    
    //设置枚举相薄类型
    NSUInteger type;
    if (assetType == kALAssetTypePhoto || assetType == kALAssetTypeUnknow) {
        
        type = ALAssetsGroupSavedPhotos;
    } else {
        
        type = ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupEvent | ALAssetsGroupFaces | ALAssetsGroupSavedPhotos | ALAssetsGroupPhotoStream;
    }
    [[HSYBaseViewController shareInstanceLibrary] enumerateGroupsWithTypes:type
                                                                usingBlock:resultsBlock
                                                              failureBlock:failureBlock];
}


- (void)getLastImageByGroup:(ALAssetsGroup *)group usingBlock:(void (^)(UIImage *image))block {
    //枚举回调
    void (^selectionBlock)(ALAsset*, NSUInteger, BOOL*) = ^(ALAsset* asset, NSUInteger index, BOOL* innerStop) {
        
        if (!asset) {
            return;
        }
        if (block) {
            block([UIImage imageWithCGImage:[asset thumbnail]]);
        }
    };
    
    //设置过滤类型
    [group setAssetsFilter:[ALAssetsFilter allPhotos]];
    if ([group numberOfAssets] > 0) {
        NSUInteger index  = [group numberOfAssets] - 1;
        NSIndexSet *lastPhotoIndexSet = [NSIndexSet indexSetWithIndex:index];
        //枚举最后一个Asset
        [group enumerateAssetsAtIndexes:lastPhotoIndexSet options:0 usingBlock:selectionBlock];
    }
}

@end
